const storageManager = require('../storage');

/**
 * API接口管理工具
 */
module.exports = {
  name: 'api',
  description: 'API接口管理工具，用于添加、查询和列出API接口设计',
  parameters: {
    type: 'object',
    properties: {
      action: {
        type: 'string',
        enum: ['list', 'add', 'get'],
        description: '要执行的操作: list(列出所有接口), add(添加新接口), get(获取特定接口)'
      },
      path: {
        type: 'string',
        description: '接口路径，如 /api/users'
      },
      method: {
        type: 'string',
        enum: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
        description: 'HTTP方法'
      },
      description: {
        type: 'string',
        description: '接口描述'
      },
      requestParams: {
        type: 'object',
        description: '请求参数定义，包括路径参数、查询参数和请求体'
      },
      responseSchema: {
        type: 'object',
        description: '响应数据结构定义'
      },
      auth: {
        type: 'boolean',
        description: '是否需要认证'
      },
      tags: {
        type: 'array',
        items: {
          type: 'string'
        },
        description: '接口标签，用于分类和搜索'
      }
    },
    required: ['action']
  },
  handler: async ({ action, path, method, description, requestParams, responseSchema, auth, tags }) => {
    try {
      switch (action) {
        case 'list':
          const apis = storageManager.getApis();
          return {
            apis,
            count: apis.length
          };
        
        case 'add':
          if (!path) {
            throw new Error('添加接口需要提供接口路径');
          }
          if (!method) {
            throw new Error('添加接口需要提供HTTP方法');
          }
          
          const newApi = storageManager.addApi({
            path,
            method,
            description: description || '',
            requestParams: requestParams || {},
            responseSchema: responseSchema || {},
            auth: auth || false,
            tags: tags || []
          });
          
          return {
            message: `接口 ${method} ${path} 添加成功`,
            api: newApi
          };
        
        case 'get':
          if (!path) {
            throw new Error('获取接口需要提供接口路径');
          }
          
          const apisList = storageManager.getApis();
          let api;
          
          if (method) {
            api = apisList.find(a => a.path === path && a.method === method);
          } else {
            api = apisList.filter(a => a.path === path);
          }
          
          if (!api || (Array.isArray(api) && api.length === 0)) {
            throw new Error(`未找到接口: ${method || ''} ${path}`);
          }
          
          return {
            api
          };
        
        default:
          throw new Error(`未知操作: ${action}`);
      }
    } catch (error) {
      return {
        error: error.message
      };
    }
  }
}; 